import extend from 'dva-model-extend';
import settings from '@/settings';
import model from '@/baseModel';
import { getOne, getTable, getNodes, getList } from '@/services/dictionary';

const { pagination } = settings;

export default extend(model, {
  namespace: 'dictionary',
  state: {
    fields: [{}]
  },
  effects: {
    *reset(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          data: undefined,
          fields: [{}]
        },
      });
    },
    *fetchOne({ payload }, { call, put }) {
      const { data = {} } = yield call(getOne, payload);
      yield put({
        type: 'updateState',
        payload: {
          data
        },
      });
    },
    *fetchTable({ payload }, { call, put }) {
      const { data = {} } = yield call(getTable, payload);
      const {
        fields = [{}]
      } = data
      yield put({
        type: 'updateState',
        payload: {
          data,
          fields
        },
      });
    },
    *fetchTree({ payload }, { call, put }) {
      const { data } = yield call(getNodes, payload);
      yield put({
        type: 'updateState',
        payload: {
          data
        },
      });
    },
    *fetchList({ payload = pagination }, { call, put }) {
      const { data } = yield call(getList, payload);
      yield put({
        type: 'updateState',
        payload: {
          list: data,
          params: payload,
        },
      });
    }
  },
});
